<template>
  <div @click="backToTop" id="back-top">
    <svg-icon icon-class="backtop" class-name="mt10"></svg-icon>
  </div>
</template>

<script>
import { debounce } from "@/utils";
export default {
  data() {
    return {
      visibilityHeight: 100, // 距离顶部多少 px 后出现返回顶部按钮
      dom: null, // 返回顶部按钮的元素
      interval: null, // 返回顶部循环任务的标识
      backPosition: 0 // 初始化的位置，返回顶部之后，就会回到这个位置
    };
  },
  mounted() {
    this.dom = document.getElementById("back-top");
    window.addEventListener("scroll", debounce(this.handleScroll));
  },
  methods: {
    /**
     * 监听窗口滚动事件
     */
    handleScroll() {
      this.dom.style.display =
        window.pageYOffset > this.visibilityHeight ? "block" : "none";
    },
    backToTop() {
      const start = window.pageYOffset;
      let i = 0;
      this.interval = setInterval(() => {
        const next = Math.floor(this.easeInOutQuad(10 * i, start, -start, 500));
        if (next <= this.backPosition) {
          window.scrollTo(0, this.backPosition);
          clearInterval(this.interval);
        } else {
          window.scrollTo(0, next);
        }
        i++;
      }, 16.7);
    },
    easeInOutQuad(t, b, c, d) {
      if ((t /= d / 2) < 1) return (c / 2) * t * t + b;
      return (-c / 2) * (--t * (t - 2) - 1) + b;
    }
  }
};
</script>

<style scoped>
#back-top {
  width: 40px;
  text-align: center;
  height: 40px;
  cursor: pointer;
  background: #fff;
  border-radius: 5px;
  position: fixed;
  bottom: 50px;
  right: 50px;
  display: none;
}
</style>
